package com.webdrider.manager.action.blog;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import com.common.dao.interfaces.IDao;
import com.common.dao.util.Criteria;
import com.common.dao.util.Order;
import com.common.dao.util.QueryOperation;
import com.common.manager.abstracts.AbstractManager;
import com.common.security.exceptions.DatabaseException;
import com.common.security.exceptions.ManagerException;
import com.webdrider.dao.action.blog.PostDao;
import com.webdrider.dao.interfaces.IPostDao;
import com.webdrider.manager.interfaces.IPostManager;
import com.webdrider.model.action.blog.Post;
import com.webdrider.security.exceptions.BlogException;

public class PostManager extends AbstractManager<Post> implements IPostManager {

	private IPostDao postDao;
	
	public PostManager() {
		postDao = new PostDao();
	}
	
	@Override
	protected IDao<Post> getDao() {
		return postDao;
	}
	
	@Override
	public Post getPost(String insensitiveTitle) throws BlogException, ManagerException {
		try {
			List<Criteria> criterias = new ArrayList<Criteria>();
			
			criterias.add(new Criteria(Post.INSENSITIVE_TITLE, insensitiveTitle, QueryOperation.EQUALS, true));
			List<Post> posts = postDao.getByCriteria(criterias);
			
			if (posts.size() == 0) {
				Logger.getAnonymousLogger().severe("WTF ?" + posts.size());
				throw new BlogException(BlogException.POST_NOT_FOUND);
			} else if (posts.size() == 1) {
				Logger.getAnonymousLogger().severe("WTF ?" + posts.size());
				return posts.get(0);
			} else {
				Logger.getAnonymousLogger().severe("WTF ?" + posts.size());
				throw new BlogException(BlogException.MULTIPLE_POSTS_FOUND);
			}
		} catch (DatabaseException e) {
			Logger.getAnonymousLogger().severe("WTF ?" + e);
			throw new ManagerException(ManagerException.DATABASE_EXCEPTION);
		}
	}

	@Override
	public void save(Post post) throws ManagerException {
		//FIXME Critical priority: Add a map for comments and categories
		post.setInsensitiveTitle(convertInsensitiveTitle(post.getTitle()));
		super.save(post);
	}

	@Override
	public Post getLatestPost() throws BlogException, ManagerException {
		try {
			List<Order> orders = new ArrayList<Order>();
			
			orders.add(new Order(Post.DATE, QueryOperation.DESC));
			List<Post> posts = postDao.getByOrder(orders);
			
			if (posts.size() == 0) {
				Logger.getAnonymousLogger().severe("WTF ?" + posts.size());
				throw new BlogException(BlogException.POST_NOT_FOUND);
			} else {
				Logger.getAnonymousLogger().severe("WTF ?" + posts.size());
				return posts.get(0);
			}
		} catch (DatabaseException e) {
			Logger.getAnonymousLogger().severe("WTF ?" + e);
			throw new ManagerException(ManagerException.DATABASE_EXCEPTION);
		}
	}
	
	private String convertInsensitiveTitle(String title) {
		String insensitiveTitle = title.replaceAll("[<>\'\"]", "");
		return insensitiveTitle.toLowerCase();
	}
}
